package com.atguigu.wordcount.myinputformat;

import com.atguigu.util.HdfsUtil;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.IOUtils;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.InputSplit;
import org.apache.hadoop.mapreduce.RecordReader;
import org.apache.hadoop.mapreduce.TaskAttemptContext;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;

import java.io.IOException;
import java.io.InputStream;

/**
 * @ClassName MyRecordReader
 * @DeScription MyRecordReader
 * @Author 剧情再美终是戏
 * @Date 2019/11/18 13:09
 * @Version 1.0
 **/
public class MyRecordReader extends RecordReader<Text, BytesWritable> {

    private Text key;
    private BytesWritable value;
    private String filePath;
    private FileSystem fs;
    private InputStream is;
    private int fileLength;
    private boolean flag = true; // 保证只读取一次

    public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException {
        if (null != inputSplit && null != taskAttemptContext) {
            FileSplit fileSplit = (FileSplit) inputSplit;
            fileLength = (int) fileSplit.getLength();
            Path path = fileSplit.getPath();
            filePath = path.toString();
            fs = HdfsUtil.getFileSystem(taskAttemptContext.getConfiguration());
            is = fs.open(path);
        }
    }

    public boolean nextKeyValue() throws IOException, InterruptedException {
        if (flag) {
            if (null == key) {
                key = new Text();
            }
            if (null == value) {
                value = new BytesWritable();
            }
            // 封装key
            key.set(filePath);

            // 组装value
            byte[] bb = new byte[fileLength];
            IOUtils.readFully(is, bb, 0, bb.length);
            value.set(bb, 0 ,bb.length);

            flag = false; // 更新标记位
            return true;
        }
        return false;
    }

    public Text getCurrentKey() throws IOException, InterruptedException {
        return key;
    }

    public BytesWritable getCurrentValue() throws IOException, InterruptedException {
        return value;
    }

    public float getProgress() throws IOException, InterruptedException {
        return 0;
    }

    public void close() throws IOException {
        if(null != is) {
            IOUtils.closeStream(is);
        }
        if(null != fs) {
            fs.close();
        }
     }
}
